import { Injectable, Injector, Inject } from '@angular/core';
import { Router } from '@angular/router';
import {
    HttpInterceptor, HttpRequest, HttpHandler,
    HttpSentEvent, HttpHeaderResponse, HttpProgressEvent, HttpResponse, HttpUserEvent,
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { catchError } from 'rxjs/operators';
import { mergeMap } from 'rxjs/operators';
import { environment } from '@env/environment';
import { ITokenService, DA_SERVICE_TOKEN, TokenService } from '@delon/auth';
import { AjaxResponse } from 'app/model/rest-model';

/**
 * 默认HTTP拦截器 其注册细节见 `app.module.ts`
 */
@Injectable()
export class DefaultInterceptor implements HttpInterceptor {

    constructor(
        private injector: Injector, // injector 注入器
        @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService // 存取token的业务
    ) { }

    intercept(req: HttpRequest<any>, next: HttpHandler):
        Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any>> {

        // 统一加上服务端前缀
        let url = req.url;
        if (!url.startsWith('https://') && !url.startsWith('http://')) {
            url = environment.SERVER_URL + url;
        }

        // 统一加上请求token
        let token = this.tokenService.get().token;
        console.log(token);
        const newReq = req.clone({
            url: url,
            headers: req.headers.set('authorization', `${token}`)
        });

        return next.handle(newReq).pipe(
            mergeMap((event: any) => {
                // 允许统一对请求错误处理
                if (event instanceof AjaxResponse && event.responseCode.code !== 200) {
                    return of(<any>{ status: event.responseCode.code, errorMsg: event.errorMsg });
                }
                return of(event);
            }), catchError((res: HttpResponse<any>) => {
                // 业务处理：一些通用操作
                switch (res.status) {
                    case 402: this.goLogin(); break; // token无效
                    case 415: console.log(`业务错误`); break; // 业务级错误
                    case 404: break; // 跳转到404页面
                }
                // 返回错误状态码和错误信息
                return of(<any>{ status: res.status });
            })
        );
    }

    private goLogin() {
        this.injector.get(Router).navigate(['/user/auth']);
    }
}
